package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2020/4/6 14:58
 */
@Component
public class ManagerFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }
    //过滤器的业务
    @Override
    public Object run() throws ZuulException {
        //1.得到请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //1.1)放行一些特殊资源
        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        if(request.getRequestURI().equals("/login")){
            return null;
        }
        //2.得到请求头
        String header = request.getHeader("Authorization");
        //3.判断是否有值，是否以Bearer 开头
        if(StringUtils.isNotBlank(header) && header.startsWith("Bearer ")){
            //4.得到token值
            String token = header.substring(7);
            //5.解析token
            Claims claims = jwtUtil.parseJWT(token);
            //6.判断claims是否有值
            if(claims != null){
                //6.1)得到角色
                String roles = (String) claims.get("roles");
                //6.2)看是否是管理员角色
                if("admin".equals(roles)){
                    currentContext.addZuulRequestHeader("Authorization",header);
                    return null;
                }
            }
        }
        //7.拦截不让其向下执行
        currentContext.setSendZuulResponse(false);      //设置网关不再执行响应
        currentContext.setResponseStatusCode(403);      //设置网关的响应码为403
        currentContext.setResponseBody("无访问权限！");   //设置响应体内容
        currentContext.getResponse().setContentType("text/html;charset=utf-8"); //设置响应页面的格式
        return null;
    }
}
